#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import MySQLdb
import logging.config
import mysql_conn_pool as _pool
import file_io
logging.config.fileConfig("log/logging.ini")
logger = logging.getLogger("mysql")
log_error = logging.getLogger("error")
# 修改默认编码为"utf-8"
default_encoding = "utf-8"

# if (default_encoding != sys.getdefaultencoding()):
#     reload(sys)
#     sys.setdefaultencoding(default_encoding)

class MYSQL_Manager():

    def __init__(self,**mysql_config):
        _pool.Mysql_Config(**mysql_config)
        self._conn_model = _pool.dbConnet_Model()
        logger.debug(self._conn_model)
        self.conn = self._conn_model.get_conn()
        self.cursor = self._conn_model.get_cursor()

        self.isconnect = self._conn_model.isconnect
        self._dbError = self._conn_model._dbError

    def execute(self,sql='',param=()):
        if self.isconnect :
            try:
                if param:
                    rowcount = self.cursor.execute(sql,param)
                else:
                    rowcount = self.cursor.execute(sql)
                self.exec_msgs = u"查询： '%s'\n\n 返回 %d lines"% (sql,rowcount)
                logger.debug(self.exec_msgs)
                return rowcount
            except Exception as e:
                self.exec_msgs = u"查询： '%s'\n\n错误代码 %d \n\n%s"% (sql,e.args[0],e.args[1])
                logger.debug(e)
                return -1
        else:
            return -1

    def selectAll(self,sql='',param=()):
        try:
            rowcount = self.execute(sql,param)
            if rowcount > 0:
                result = self.cursor.fetchall()
                logger.debug("return %d row", rowcount)
                return result
            else:
                return 0
        except Exception as e:
            error = 'selectall except  ', e.args
            log_error.debug(error)
            return 0

    def custom_sql_exec(self, sql='', param=()):
        try:
            rowcount = self.execute(sql, param)
            if rowcount > 0:
                self.conn.commit()
                result = self.cursor.fetchall()
                fields = self.cursor.description
                # logger.debug("return %d row", rowcount)
                #print type(rowcount)
                return rowcount, result, fields
            else:
                self.conn.rollback()
                return None,None,None
        except Exception as e:
            error = 'selectall except  ', e.args
            log_error.debug(error)
            return None,None,None

    def close(self):
        return self._conn_model.close()

class MYSQL_shows():
    def __init__(self,mysql_manager):
        self.sql_manager = mysql_manager


    def show_databases(self):
        __sql_showdatabases = "show databases"
        #count = self.sql_manager.execute(__sql_showdatabases)
        databases_res = self.sql_manager.selectAll(__sql_showdatabases)
        return databases_res

    def show_tables(self,db):
        __sql_use = "use `%s`" % db
        __sql_showtables = "show tables"
        count = self.sql_manager.execute(__sql_use)
        if count >= 0 :  # 判断是否选择数据库成功
            tables_res = self.sql_manager.selectAll(__sql_showtables)
            return tables_res
        else:
            return ["no databases"]

    def show_tab_values(self, table):
        __sql_tab_values = "SELECT /*!40001 SQL_NO_CACHE */ * FROM %s" % table

        _tab_values = self.sql_manager.selectAll(__sql_tab_values)
        logger.critical(_tab_values)
        return _tab_values

    def show_tab_fields(self, table):
        __sql_tab__fileds = "desc  %s" % table
        _tab_fileds = self.sql_manager.selectAll(__sql_tab__fileds)
        return _tab_fileds

    def close(self):
        return self.sql_manager.close()
# class _TableModel(object):
#     '''
#     fieldname
#     '''
#     table_info = {}
#
#     def __init__(self,sql_manager, table_name):
#         self._table_name = table_name
#         self.conn = sql_manager.conn
#         self.cursor = sql_manager.cursor
#         self.field_info()
#
#     def field_info(self):
#         # if self._table_name in _TableModel.table_info.keys():
#         #     return _TableModel.table_info[self._table_name]
#         cursor = self.cursor
#         try:
#             #self.cursor.execute('use  psm70_0615')
#             self.cursor.execute('desc  %s' % self._table_name)
#             fields = self.cursor.fetchall()
#             #print fields
#         except:
#             #raise Exception, "con't find field info"
#             log_error.exception("con't find field info")
#         else:
#             self.conn.commit()
#             _TableModel.table_info[self._table_name] = _FieldModel(fields)
#             return True
#
#     def execute(self, sql='', param=()):
#         try:
#             if param:
#                 rowcount = self.cursor.execute(sql, param)
#             else:
#                 rowcount = self.cursor.execute(sql)
#             logger.info("execute '%s'", sql)
#             return rowcount
#
#         except Exception as e:
#             log_error.error(e)
#
#     def primary_key(self):
#         '''
#         返回primary key的字段名称 如果没有则返回为None
#         '''
#         return _TableModel.table_info[self._table_name].primary_key_name()
#
#     def foreign_key(self):
#         '''
#         返回外键的名称 由于一张表中可以有多个外键 所以返回的是一个以字段名组成的列表 若没有外键则返回一个空的列表
#         '''
#         return _TableModel.table_info[self._table_name].foreign_key_name()
#
# class _FieldModel(object):
#     '''
#     mysql mysql的字段内型有许多种：整形：tinyint(1) smallint(2) mediumint(3) int(4) bigint(8)
#     字符:char varchar text
#     时间:year date time datetime
#
#     (u'id', u'int(11)', u'NO', u'PRI', None, u'auto_increment')
#     (u'time', u'int(11)', u'NO', u'', None, u'')
#     (u'title', u'varchar(100)', u'NO', u'', None, u'')
#     (u'content', u'longtext', u'NO', u'', None, u'')
#     (u'uid_id', u'int(11)', u'NO', u'MUL', None, u'')
#     '''
#     _type_list = ['tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'char', 'varchar', 'text',
#                   'year', 'data', 'time', 'datetime']
#
#     # field_name, _type, value, is_primay_key = False, is_foreign_key = False
#     def __init__(self, field_info=[]):
#         '''
#         这里为什么使用的是列表而不是字典的原因是由于 通过SQL语句查询字段信息返回的是一个
#         有顺序的列表，如果转换成字典就会变成无序的，那么在上面进行SELECT查询的时候，返回的
#         内容正好和这个_FieldModel的顺序是对应的
#         '''
#         self._field = []
#         self._foreign_key = []
#         self._primary_key = None  # only one primary key
#         for field in field_info:
#             self._field.append(dict(name=field[0], type=field[1], primary=True if field[3] == 'PRI' else False,
#                                     foreign=True if field[3] == 'MUL' else False,default=field[4],extra=field[5]))
#
#             if field[3] == 'PRI':
#                 self._primary_key = field[0]
#             elif field[3] == 'MUL':
#                 self._foreign_key.append(field[0])
#
#     def __iter__(self):
#         return iter(self._field)
#
#     def primary_key_name(self):
#         return self._primary_key
#
#     def foreign_key_name(self):
#         return self._foreign_key

###
# def tab_mod_test():
#     sql_manager = MYSQL_Manager()
#     i = 1
#     sql_1 = "use psm70_0615"
#     sql_2 = "show tables"
#     count = sql_manager.execute(sql_1)
#     result = sql_manager.selectAll(sql_2)
#     for res in result:
#         table_mod = _TableModel(sql_manager, res[0])
#         for field in table_mod.table_info[res[0]]._field:
#             i += 1
#             print field
#     print i

class MysqlDump(object):
    def __init__(self,mysql_manager,db,filename):
        self.sql_manager = mysql_manager
        self.db = db
        self.filename = filename
        self.dumpsql = ""# 储存拼接的sql语句

        self.sql_use = "USE `%s`" % self.db
        self.sql_s_db = "SHOW CREATE DATABASE IF NOT EXISTS `%s`" % self.db
        self.sql_s_tab = "show tables"

        self.sql_use_information = "use `information_schema`"

        self.sql_set_ses = "SET SESSION character_set_results = 'binary'"

    def dump_exec(self,lock = False):
        #t = 1
        self.lock =lock
        logger.debug("dump_exec start")
        self.__set_exec() # 执行数据查询前，执行相关设置
        count = self.sql_manager.execute(self.sql_use)
        if count == 0 :# 判断是否选择数据库成功
            self.__set_exec() # 备份前执行相关设置

            toolnote = self.__build_dumptoolnote()
            dumpsqlnot = self.__build_dumpsqlnote()
            self.dumpsql = "".join([toolnote+dumpsqlnot]) # 拼接开头注释
            #self.__build_dumpsql(toolnote, dumpsqlnot) # 拼接注释

            # 获取DB创建语句，返回结果为tuple类型，第一个元素为DB名，第二个元素为表结构
            # 所以用table_create = tabcreate_res[0][1]表示
            dbcreate_res = self.sql_manager.selectAll(self.sql_s_db)
            db_create = dbcreate_res[0][1]
            self.dumpsql = "".join([self.dumpsql, db_create,";\n\n",self.sql_use,";\n\n"]) # 拼接db_create，use_db
            #self.__build_dumpsql(db_create,";\n\n",self.sql_s_db,";\n\n")

            self.__saveporint()# 记录
            tables_res = self.sql_manager.selectAll(self.sql_s_tab)

            table_name = [ tn[0] for tn in tables_res]# 因tn=(u'tablename',),所以需去第一位元素
            table_value = map(self.__map_tabl_value, table_name)
            table_value= "".join(table_value)
            self.dumpsql= "".join([self.dumpsql,table_value])

            # for tn in tables_res:
            #     table_name = tn[0] # 因tn=(u'tablename',),所以需去第一位元素
            #     table_create =self.__get_tablecreat(table_name) # 调用函数，获取table_create语句
            #     if table_create is None:
            #         self.__rollback_sp()  # 回滚
            #         continue
            #     dumpsql_data_into = self.__get_tablevalues(table_name)  # 调用函数，获取dumpsql_data_into语句
            #     self.__rollback_sp()  # 回滚
            #
            #     # 拼接表语句，格式为：
            #     # (dumpsql_table_head):/*Table structure for table `%s` */\n\n
            #     # DROP TABLE IF EXISTS `表名称`;\n\n
            #     # 判断是否添加锁表语句
            #     # 表结构：table_create；\n\n
            #     # /*Data for the table `表名称` */\n
            #     dumpsql_table_note = "/*Table structure for table `%s` */\n\n" % table_name
            #     dumpsql_drop_table = "DROP TABLE IF EXISTS `%s`;\n\n" % table_name
            #     sql_locktab = "LOCK TABLES `%s` WRITE;\n\n" % table_name
            #     sql_ulock = "UNLOCK TABLES;\n\n"
            #     dumpsql_data_noto = "/*Data for the table `%s` */\n\n" % table_name
            #
            #     #self.dumpsql = self.dumpsql+dumpsql_table_note+dumpsql_drop_table # 拼接表注释，删除表语句
            #     self.dumpsql = "".join([self.dumpsql, dumpsql_table_note, dumpsql_drop_table])# 拼接表注释，删除表语句
            #     #self.__build_dumpsql(dumpsql_table_note,"\n\n",dumpsql_drop_table)# 拼接表注释，删除表语句
            #
            #     #self.dumpsql = self.dumpsql+ table_create+";\n\n"+dumpsql_data_noto
            #     self.dumpsql = "".join([self.dumpsql, table_create, ";\n\n", dumpsql_data_noto])# 拼接表结构，换行,数据注释
            #     #self.__build_dumpsql(table_create,";\n\n")  # 拼接表结构，加换行
            #     #self.__build_dumpsql(dumpsql_data_noto) # 拼接数据注释
            #
            #     if lock:  # 判断是否添加锁表语句
            #         #self.dumpsql = self.dumpsql+ sql_locktab+ dumpsql_data_into+ sql_ulock # 拼接注释
            #         self.dumpsql = "".join([self.dumpsql, sql_locktab, dumpsql_data_into, sql_ulock])  # 拼接注释
            #         # self.__build_dumpsql(*sql_locktab)
            #         # self.__build_dumpsql(*dumpsql_data_into)
            #         # self.__build_dumpsql(*sql_ulock)
            #     else:
            #         #self.dumpsql = self.dumpsql+ dumpsql_data_into # 拼接注释
            #         self.dumpsql = "".join([self.dumpsql, dumpsql_data_into])  # 拼接注释
            #         #self.__build_dumpsql(*dumpsql_data_into) # 拼接注释

            self.__release_sp() # 释放

            self.__build_trigger() # 拼接触发器

            func_typedict = ["Function", "function", "FUNCTION"]
            proc_typedict = ["Procedure", "procedure", "PROCEDURE"]
            self.__build_func_proc(func_typedict)  # 拼接函数
            self.__build_func_proc(proc_typedict)  # 拼接存储过程

        self.__write_data()
        logger.debug("dump_exec end")

    def __map_tabl_value(self,table_name):
        table_create = self.__get_tablecreat(table_name)  # 调用函数，获取table_create语句

        if table_create > 0:
            dumpsql_data_into = self.__get_tablevalues(table_name)  # 调用函数，获取dumpsql_data_into语句
            self.__rollback_sp()  # 回滚
            dumpsql_table_note = "/*Table structure for table `%s` */\n\n" % table_name
            dumpsql_drop_table = "DROP TABLE IF EXISTS `%s`;\n\n" % table_name
            sql_locktab = "LOCK TABLES `%s` WRITE;\n\n" % table_name
            sql_ulock = "UNLOCK TABLES;\n\n"
            dumpsql_data_noto = "/*Data for the table `%s` */\n\n" % table_name
            dumpsql = "".join([dumpsql_table_note, dumpsql_drop_table])  # 拼接表注释，删除表语句
            dumpsql = "".join([dumpsql, table_create, ";\n\n", dumpsql_data_noto])  # 拼接表结构，换行,数据注释
            if self.lock:  # 判断是否添加锁表语句
                dumpsql = "".join([dumpsql, sql_locktab, dumpsql_data_into, sql_ulock])  # 拼接注释
            else:
                dumpsql = "".join([dumpsql, dumpsql_data_into])  # 拼接注释
        else:
            self.__rollback_sp()  # 回滚
            dumpsql = ""
        return dumpsql

    def __set_exec(self):
        """
        设置mysql模式
        :return:
        """
        #logger.info("_set_exec start")
        sql_set1 = "/*!40100 SET @@SQL_MODE='' */"
        sql_set2 = "FLUSH /*!40101 LOCAL */ TABLES"
        sql_set3 = "FLUSH TABLES WITH READ LOCK"
        sql_set4 = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ"
        sql_set5 = "START TRANSACTION /*!40100 WITH CONSISTENT SNAPSHOT */"
        sql_set6 = "SHOW VARIABLES LIKE 'gtid\_mode'" # 不会利用
        sql_set7 = "SHOW MASTER STATUS"# 不会利用
        sql_set8 = "UNLOCK TABLES"
        self.sql_manager.execute(sql_set1)
        self.sql_manager.execute(sql_set2)
        self.sql_manager.execute(sql_set3)
        self.sql_manager.execute(sql_set4)
        self.sql_manager.execute(sql_set5)
        self.sql_manager.execute(sql_set8)
        #logger.info("_set_exec end")

    def __saveporint(self):
        sql_SAVEPOINT = "SAVEPOINT sp"
        self.sql_manager.execute(sql_SAVEPOINT)
    def __rollback_sp(self):
        sql_ROLLBACK = "ROLLBACK TO SAVEPOINT sp"
        self.sql_manager.execute(sql_ROLLBACK)
    def __release_sp(self):
        sql_RELEASE = "RELEASE SAVEPOINT sp"
        self.sql_manager.execute(sql_RELEASE)

    def __get_tablecreat(self,table_name):
        """
        # show table status like %s查询表的状态，结果的作用未明白，预留
        # SHOW CREATE TABLE %s获取表结构创建语句，返回结果为tuple类型，第一个元素为表名，第二个元素为表结构
        # 所以用table_create = tabcreate_res[0][1]表示表结构创建语句
        """
        sql_tabstatus = "show table status like '%s' " % table_name
        tabstatus_res = self.sql_manager.selectAll(sql_tabstatus)
        #print tabstatus_res[0][-1]
        if tabstatus_res[0][-1] is "VIEW":
            return None
        else:
            sql_tabcreate = "SHOW CREATE TABLE `%s`" % table_name
            tabcreate_res = self.sql_manager.selectAll(sql_tabcreate)
            table_create = tabcreate_res[0][1]
            return table_create

    def __get_tablevalues(self,table_name):
        """
        :function：生成valuse插入语句
        :param table_name:
        :return: dumpsql_val_ins = "insert  into `%s` (%s) values %s\n\n"
         % (table_name, table_fileds, table_values)
         1.# sql_data =查询表数据，返回结果为tuple型，结果可以为None，结果为None省略拼接语句
         2.# cursor.description 可以直接获取表字段table_fileds，返回结果的第一位元素为字段名称，所以用table_filed[0]表示
         3.# map函数，遍历res列表，通过调用_get_str函数，把res内的元素转换成str类型
         4.# 通过“,”.join(list)的方式连接map函数转换出来的字符
         5.# list表达式生成方式，比使用for循环可以节省生成的时间，内存
         6.# dumpsql_val_ins = 拼接表数据插入语句:insert  into `表名称` (表字段) values 表数据
        """
        logger.debug("__get_tablevalues for %s start"% table_name)
        sql_data = "SELECT /*!40001 SQL_NO_CACHE */ * FROM `%s`" % table_name
        table_data_res = self.sql_manager.selectAll(sql_data)
        if table_data_res >0 :
            table_fileds_res = self.sql_manager.cursor.description
            table_fileds = ["`" + table_filed[0] + "`" for table_filed in table_fileds_res] # list表达式生成方式
            table_fileds = ",".join(table_fileds)
            logger.debug("table_value-start")
            t_list = ["(" + ",".join(map(self._get_str, res)) + ")" for res in table_data_res]# 使用到了join，map函数，self._get_str为自定义函数
            table_values = ",".join(t_list)
            logger.debug("table_value-join")
            dumpsql_data_into = "insert  into `%s`(%s) values %s;\n\n" % (
                table_name, table_fileds, table_values)
            logger.debug("table_value-inser")
            # if table_name == "t_device":
            #     print len(t_list)
            #     print len(table_values)
        else:
            dumpsql_data_into = ""

        #logger.info("__get_tablevalues end")
        return dumpsql_data_into

    def __build_trigger(self,DEFINER=True):
        #logger.info("__build_trigger start")

        sql_s_tri = "SELECT /*!40001 SQL_NO_CACHE */ * FROM `INFORMATION_SCHEMA`.`TRIGGERS` WHERE TRIGGER_SCHEMA ='%s'" % self.db
        triggers_res = self.sql_manager.selectAll(sql_s_tri)
        if triggers_res >0 :
            for triggers in triggers_res:
                """
                # TRI_DEFINER = triggers[-4] # 定义者
                # TRI_NAME = triggers[2] # 触发器名
                # ATC_TIMING = triggers[11] # 动作 安排（之前之后）
                # EVENT_MANAPULATION = triggers[3] # 触发操作
                # EVENT_TABLE = triggers[6] # 触发表名
                # ATC_ORIENTATION = triggers[10] # 动作方向
                # EVENT_STATEMENT = triggers[9] # 内容
                """
                if DEFINER:
                    _DEFINER = triggers[-4]
                    definer_s = _DEFINER.split("@")
                    TRI_DEFINER = "/*!50003 DEFINER = '%s'@'%s' */" %(definer_s[0],definer_s[1])
                else:
                    TRI_DEFINER = ""
                dumpsql_trifortab = "/* Trigger structure for table `%s` */\n\n" % triggers[6]
                dumpsql_triname = "/*!50003 DROP TRIGGER*//*!50032 IF EXISTS */ /*!50003 `%s` */$$\n\n" % triggers[2]

                sql_tri = "/*!50003 CREATE */ %s /*!50003 TRIGGER `%s` %s %s ON `%s` FOR EACH %s %s */$$\n\n\n" \
                      % (TRI_DEFINER, triggers[2], triggers[11], triggers[3], triggers[6], triggers[10], triggers[9])
                dumpsql_tri = dumpsql_trifortab+"DELIMITER $$\n\n"+dumpsql_triname+sql_tri+"DELIMITER ;\n\n"
                self.dumpsql = "".join([self.dumpsql, dumpsql_tri])

                logger.debug("build: %s "% triggers[2])
        #logger.info("__build_trigger start")

    def __build_func_proc(self,_typedict):
        """
        ###func_typedict =["Function","function", "FUNCTION"]
        ###proc_typedict =["Procedure","procedure", "PROCEDURE"]
        ###由于function 与 procedure格式类型，获取结果的方式一致，所以采用替换关键字生成语句
        """
        sql_s_funcnames = "SELECT `SPECIFIC_NAME` FROM `INFORMATION_SCHEMA`.`ROUTINES` " \
                     "WHERE `ROUTINE_SCHEMA` = '%s'AND ROUTINE_TYPE = '%s'"% (self.db, _typedict[2])
        funcnames_res = self.sql_manager.selectAll(sql_s_funcnames)

        if funcnames_res >0 :
            funcslist =[ self.__getcreate_fun_pro(funcname[0],_typedict) for funcname in funcnames_res]
            funcs = "".join(funcslist)
            self.dumpsql = "".join([self.dumpsql,funcs])

    def __getcreate_fun_pro(self,name,_typedict):
        ###func_typedict =["Function","function", "FUNCTION"]
        ###proc_typedict =["Procedure","procedure", "PROCEDURE"]
        _note = "/* %s  structure for %s  `%s` */\n\n"% (_typedict[0], _typedict[1],name)
        _drop = "/*!50003 DROP %s IF EXISTS `%s` */;\n"% (_typedict[2], name)
        _sql_show_ = "SHOW CREATE %s %s" % (_typedict[2], name)
        _creates = self.sql_manager.selectAll(_sql_show_)
        if _creates >0:
            res = "".join([_note,_drop,"DELIMITER $$\n\n/*!50003 ", _creates[0][2],"*/$$\nDELIMITER ;\n\n"])
            return res
        else:
            #print _creates
            return ""

    def __build_dumptoolnote(self):

        toolnote ="/*" \
           "pthon_mysql_tools-v1.0 for ljt\n" \
           ": Database - %s\n" \
           "***************************************************************\n" \
           "*/\n\n"% self.db
        return toolnote

    def __build_dumpsqlnote(self):
        """
        储存相关语句，后续可以根据设置修改
        :return:
        """
        dumpsql_note = "/*!40101 SET NAMES utf8 */;\n\n" \
                    "/*!40101 SET SQL_MODE=''*/;\n\n" \
                    "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n" \
                    "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n" \
                    "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n" \
                    "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n"
        #dumpsql_note = sql_note1+sql_note2+sql_note3+sql_note4+sql_note5+sql_note6
        return dumpsql_note

    # def __build_dumpsql(self,*dsqls):
    #     #弃用，效率太低
    #     #for dsql in dsqls:
    #     self.dumpsql= ["".join([self.dumpsql,dsql]) for dsql in dsqls]

    def __write_data(self):
        logger.debug("write_data start")
        f = file_io.file()
        self._iswrite, self._write_msg = f.write(self.dumpsql,self.filename)
        logger.debug("write_data end status is %s"% (str(self._iswrite)))

    def get_iswrite_data(self):
        return self._iswrite, self._write_msg
        #return typ, msg

    def _get_str(self,v):
        # _get_str函数，由于mysql返回的值有long，None等类型，需要根据实际转换成str
        if type(v) is long :
            v = str(v)
        if type(v) is int :
            v = str(v)
        elif v is None:
            v = "NULL"
        else:
            v = str(v)
            v = "'" + v + "'"
        return v



if __name__ == '__main__':
    mysql_manager = MYSQL_Manager()
    mysql_show = MYSQL_shows(mysql_manager)
    dbs = mysql_show.show_databases()

    print type(dbs)
    print dbs[1][0]
    tables = mysql_show.show_tables(dbs[1][0])
    datas = mysql_show.show_tab_values(tables[0][0])
    print datas

    #md = MysqlDump()
   # md.dump_exec()

"""
笔记
使用list表达式生成方式
list通过“,”.join(list)的方式转换成srt方式
"""
    # sql_data = "SELECT /*!40001 SQL_NO_CACHE */ * FROM %s" % "t_bay"
    # table_data_res = sql_manager.selectAll(sql_data)
    # #print table_data_res
    # if table_data_res is not None:
    #     # list表达式生成方式
    #     # map函数，遍历res列表，通过调用_get_str函数，把res元素一一转换
    #     t_list = ["("+",".join(map(_get_str, res))+")" for res in table_data_res ]
    #     # for循环生成方式
    #     #  for res in table_data_res:
    #     #    # map函数，遍历res列表，通过调用_get_str函数，把res元素一一转换
    #     #     res = ",".join(map(_get_str,res))
    #     #     res = "("+res+")"
    #     #     t_list.append(res)
    #     table_datas = ",".join(t_list)
    # print table_datas
